/**
 * SliderController
 *
 * @description :: Server-side logic for managing sliders
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */

module.exports = {
  index: function (req, res) {
    Slider.find().then(function (result) {
      console.log(result);
      res.view('admin/slider', {data: result, layout: 'admin/layout'});
    })
  },

  createSlider: function (req, res) {
    var title = req.body.title_1;
    var remark = req.body.title_2;

    var file = req.file('slider_img');
    console.log(file);

    file.upload({dirname: require('path').resolve(sails.config.appPath, 'assets/slider_img')}, function (err, uploadedFiles) {
      if (err) return res.serverError(err);
      console.log(uploadedFiles);
      var arr = uploadedFiles[0].fd.split('/');
      var imgName = arr[arr.length-1];
      Slider.create({title: title, remark: remark, img: imgName}).then(function (result) {
        console.log(result);
        res.redirect('/admin/slider');
      }).catch(function (err) {
        res.serverError(err)
      })
    })
    // Slider.create({title: title, remark: remark, img: 'test'}).then(function (result) {
    //   console.log(result);
    //   file.upload(function (err, fileUploaded) {
    //     if (err) return res.serverError(err);
    //     res.send({file: fileUploaded, info: result});
    //   })
    // })
  },

  deleteSlider: function (req, res) {
    var id = req.params.id;
    Slider.destroy([id]).exec(function (err) {
      if (err) return res.serverError(err);
      res.redirect('/admin/slider');
    })
  }
};

